package com.gobo.jinghuimall.product.exception;

import com.gobo.common.exception.BizCodeEnum;
import com.gobo.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * @author guanboStart
 */
@Slf4j
@RestControllerAdvice("com.gobo.jinghuimall.product.controller")
public class JinghuimallControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R MyVaildException(MethodArgumentNotValidException e) {
        log.error("数据校验出现异常：{},异常类型：{}", e.getMessage(), e.getClass());
        HashMap<String, String> hashMap = new HashMap<>();
        BindingResult bindingResult = e.getBindingResult();
        bindingResult.getFieldErrors().forEach((fieldError) -> {
            hashMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(), BizCodeEnum.VALID_EXCEPTION.getMessage())
                .put("data", hashMap);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable e) {
        log.error("全局异常：{},异常类型：{}\n其他信息{}", e.getMessage(), e.getClass(),e.getStackTrace());
        return R.error(BizCodeEnum.UNKONW_EXCEPTON.getCode(), BizCodeEnum.UNKONW_EXCEPTON.getMessage())
                ;
    }

}
